package com.xjm.config;

import com.xjm.entity.model.UsersModel;
import com.xjm.utils.AdminContext;
import com.xjm.utils.RedisUtil;
import com.xjm.constant.AppConst;
import com.xjm.entity.model.AdminModel;
import com.xjm.excption.NoLoginException;
import com.xjm.utils.UserContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 自定义拦截器，进行用户验证
 */
@Component
@RequiredArgsConstructor
public class MyInterceptor implements HandlerInterceptor {

    private final RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authorization = request.getHeader("Authorization");
        if (authorization == null) throw new NoLoginException("请先登录!");
        String token = authorization.substring(7);
        if (redisUtil.get(AppConst.TOKEN_PREFIX + token) instanceof AdminModel adminModel) {
            AdminContext.setAdminId(adminModel.getId());
        } else if (redisUtil.get(AppConst.USER_TOKEN_PREFIX + token) instanceof UsersModel usersModel) {
            UserContext.setUserId(usersModel.getId());
        } else {
            throw new NoLoginException("用户信息异常，请重新登录!");
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}
